package com.beijiteshop.shop.ui.address.fragment

import android.os.Bundle
import android.view.View
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.shop.R
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentAddAddressBinding
import com.beijiteshop.shop.model.api.response.AddressBean
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.address.vm.AddressVM
import com.beijiteshop.shop.utils.CityPickUtil
import com.blankj.utilcode.util.KeyboardUtils
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/8 19:39
 * @Description 添加地址页面
 */
class AddAddressFragment : BaseContainerFragment(R.layout.fragment_add_address){

    companion object{

        //添加地址
        const val TYPE_ADD = 1
        //编辑地址
        const val TYPE_EDIT = 2

        const val BUNDLE_TYPE = "bundle_type"
        const val BUNDLE_ADDRESS = "bundle_address"

        fun newInstance(type: Int,address: AddressBean?): AddAddressFragment {
            return AddAddressFragment().apply {
                val bundle = Bundle().apply {
                    putInt(BUNDLE_TYPE,type)
                    putParcelable(BUNDLE_ADDRESS,address)
                }
                arguments = bundle
            }
        }
    }

    private val mBinding by bindView<FragmentAddAddressBinding>()
    private var mType = TYPE_ADD
    private var mAddressBean: AddressBean? = null
    private val mAddressVM: AddressVM by viewModel()

    override fun onLazyLoad() {
    }

    override fun initView(view: View) {
        mType = arguments?.getInt(BUNDLE_TYPE)?: TYPE_ADD
        if (mType == TYPE_ADD){
            mAddressBean = AddressBean(
                "",
                "",
                "",
                "",
                "",
                "0"
            )
            mBinding.addAddressTitleBar.titleBarTitleTv.text = resources.getString(R.string.add_address)
        }else{
            mAddressBean = arguments?.getParcelable(BUNDLE_ADDRESS)
            mBinding.addAddressTitleBar.titleBarTitleTv.text = resources.getString(R.string.edit_address)
        }
        mBinding.addAddressDeleteBtn.visibility = if (mType == TYPE_ADD) View.GONE else View.VISIBLE
    }

    override fun initEvent() {

        startObserve()

        mBinding.addAddressTitleBar.titleBarBackIv.setOnClickListener {
            close()
        }

        mBinding.addAddressAddressEt.setOnClickListener {
            hideSoftInput()
            CityPickUtil.instance.show(this.requireActivity()){province, city, district ->
                val strBuilder = StringBuilder().apply {
                    append(province)
                    append(" ")
                    append(city)
                    append(" ")
                    append(district)
                }
                mBinding.addAddressAddressEt.hint = strBuilder
            }
        }

        mBinding.addAddressConfirmBtn.setOnClickListener {
            if (checkAddressInfo()){
                if (mType == TYPE_ADD){//新增地址
                    mAddressVM.addAddress(mAddressBean!!)
                }else if (mType == TYPE_EDIT){//编辑地址
                    mAddressVM.updateAddress(mAddressBean!!)
                }
            }
        }

        mBinding.addAddressSwitch.setOnCheckedChangeListener { _, isChecked ->
            if (mAddressBean != null){
                setDefaultAddress(isChecked)
            }
        }

        mBinding.addAddressDeleteBtn.setOnClickListener {
            if (mAddressBean != null){
                mAddressVM.deleteAddress(mAddressBean!!.bus_AddressID)
            }
        }
    }

    override fun initData() {
        if (mType == TYPE_EDIT && mAddressBean != null){
            mBinding.address = mAddressBean
        }
    }

    /**
     * 判断信息是否填写完整
     */
    private fun checkAddressInfo(): Boolean{
        if (mAddressBean != null){
            mAddressBean!!.consignee = mBinding.addAddressConsigneeEt.text.toString()
            mAddressBean!!.phone = mBinding.addAddressPhoneEt.text.toString()
            mAddressBean!!.city = if(mBinding.addAddressAddressEt.hint != null) mBinding.addAddressAddressEt.hint.toString() else ""
            mAddressBean!!.detailedAddress = mBinding.addAddressDetailAddressEt.text.toString()
            setDefaultAddress(mBinding.addAddressSwitch.isChecked)
            if (mAddressBean!!.consignee.isNotEmpty()
                && !mAddressBean!!.city.isNullOrEmpty()
                && mAddressBean!!.detailedAddress.isNotEmpty()
                && mAddressBean!!.phone.isNotEmpty()){
                return true
            }else{
                showToast(resources.getString(R.string.please_input_all_info))
                return false
            }
        }else{
            return false
        }
    }

    private fun startObserve(){
        mAddressVM.liveAddAddress.observeKt {
            //添加成功
            EventUtil.post(EventKey.UPDATE_ADDRESS,it)
            close()
        }

        //更新地址
        mAddressVM.liveUpdateAddress.observeKt {
            EventUtil.post(EventKey.UPDATE_ADDRESS,it)
            close()
        }

        //删除地址
        mAddressVM.liveDeleteAddress.observeKt {
            EventUtil.post(EventKey.UPDATE_ADDRESS,it)
            close()
        }

        mAddressVM.liveError.observeKt {
            showToast(it?:resources.getString(R.string.state_error))
        }

        mAddressVM.liveNetError.observeKt {
            showToast(it?:resources.getString(R.string.state_network_error))
        }
    }

    private fun setDefaultAddress(isDefault: Boolean){
        if (mAddressBean != null){
            mAddressBean!!.isDefault = if (isDefault) "1" else "0"
        }
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftInput(){
        try {
            KeyboardUtils.hideSoftInput(this.requireActivity())
        }catch (e: Exception){
            e.printStackTrace()
        }
    }
}